package com.ayun.member.filter;

import com.ayun.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 斌叔
 * @description: HandlerInterceptorAdapter 拦截适配器的子类，并且重写它里面的 preHandle 方法，在请求目标
 * 接口时进行拦截。
 * @create 2022-05-09 19:25
 */
@Component
public class AuthenticationFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        Boolean isLogin = false;

        // 获取请求头 Authorization: Bearer jwtToken
        final String authHeader = request.getHeader("Authorization");
        // 判断是否有token，注意 Bearer 后面有空格
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            //获取token中的内容
            final String token = authHeader.substring(7);
            //解析token
            Claims claims = jwtUtil.parseJWT(token);
            //判断token是否为空
            if (claims != null) {
                if((Boolean) claims.get("isLogin")){
                    isLogin = true;
                }

            }
        }
        if(!isLogin){
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"请登录\"}");
        }

        return isLogin;
    }
}
